import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:io';
import 'dart:convert';
import 'package:fluttertoast/fluttertoast.dart';

class PersonnalProvider with ChangeNotifier {
  String username = '游客';
  String token = '';
  String avatar = 'http://dianshan.free.idcfengye.com/avatar.jpg';
  Dio dio;

  // 登录
  void login(name,password,context)async {
    print('object');
    var formData = {
      'userName':name,
      'passWord':password
    };
    dio = new Dio();
    dio.interceptors.add(InterceptorsWrapper(
      onRequest:(RequestOptions options){
        // 在请求被发送之前做一些事情
        print('被发送之前');
        return options; 
        },
        onResponse:(Response response) {
        // 在返回响应数据之前做一些预处理
        print("响应之前");
        // print(response.headers);
        return response; // continue
        },
        onError: (DioError e) {
          // 当请求失败时做一些预处理
          print('请求失败了');
          // print(e.response.data);
          if(e.response.statusCode==401){
            Fluttertoast.showToast(
              msg: '登录过期，请重新登录',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIos: 1,
              backgroundColor: Theme.of(context).primaryColor,
              textColor: Colors.white,
              fontSize: 16.0
            );
            username = '游客';
            token = '';
          }
          print(e.response.statusCode);
          // print(e.response.headers);
          // print(e.response.request);
        return e;//continue
        }
    ));
    Response response = await dio.post('http://dianshan.free.idcfengye.com/user/login',data: formData);
    var data = json.decode(response.toString());
    if(data['code']==200){
      Fluttertoast.showToast(
        msg: "登录成功",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
      token = data['token'];
      username = name;
      avatar = 'http://dianshan.free.idcfengye.com/' + data['avatar'];
      Navigator.pop(context);
    }else {
      Fluttertoast.showToast(
        msg: data['message'],
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
    }
  }

  // 注册
  void register(name,password,context)async {
    var formData = {
      'userName':name,
      'passWord':password
    };
    dio = new Dio();
    Response response = await dio.post('http://dianshan.free.idcfengye.com/user/register',data: formData);
    var data = json.decode(response.toString());
    if(data['code']==200){
      Fluttertoast.showToast(
        msg: "注册成功",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
      Navigator.pop(context);
    }else {
      Fluttertoast.showToast(
        msg: data['message'],
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
    }
  }

  // 注销
  void out() {
    username = '游客';
    token = '';
    avatar = 'http://dianshan.free.idcfengye.com/avatar.jpg';
    notifyListeners();
  }  

  // 查找历史订单
  Future HistoryCart(context) async {
    Options options = Options(
      headers: {HttpHeaders.authorizationHeader : token},
      contentType: ContentType.parse("application/x-www-form-urlencoded")
    );
    Response response = await dio.get('http://dianshan.free.idcfengye.com/goods/getHistoryCart',options: options);
    var data = json.decode(response.toString());
    Fluttertoast.showToast(
      msg: data['message'],
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
      backgroundColor: Theme.of(context).primaryColor,
      textColor: Colors.white,
      fontSize: 16.0
    );
    if(data['message']=='您没有历史订单'){
      return 'not';
    };
    return response.toString();
    
  }

  // 删除历史订单
  void deleteCart(context) async {
    Options options = Options(
      headers: {HttpHeaders.authorizationHeader : token},
      contentType: ContentType.parse("application/x-www-form-urlencoded")
    );
    Response response = await dio.get('http://dianshan.free.idcfengye.com/goods/deleteCart',options: options);
    var data = json.decode(response.toString());
    Fluttertoast.showToast(
      msg: data['message'],
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
      backgroundColor: Theme.of(context).primaryColor,
      textColor: Colors.white,
      fontSize: 16.0
    );
  }

  // 修改密码
  void pwdUpd(oriPwd,updPwd,context)async{
    var formData = {
      'oriPwd': oriPwd,
      'updPwd': updPwd
    };
    Options options = Options(
      headers: {HttpHeaders.authorizationHeader : token},
      contentType: ContentType.parse("application/x-www-form-urlencoded")
    );
    Response response = await dio.post('http://dianshan.free.idcfengye.com/user/updPassword',data: formData,options: options);
    var data = json.decode(response.toString());
    Fluttertoast.showToast(
      msg: data['message'],
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
      backgroundColor: Theme.of(context).primaryColor,
      textColor: Colors.white,
      fontSize: 16.0
    );
    if(data['code']==200){
      out();
      Navigator.pop(context);
      notifyListeners();
    }
  }
}